/* MQTT (over TCP) Example

   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/

#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <strings.h>
#include "parameters.h"

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "freertos/queue.h"

#include "DevicesQueue.h"
#include "taskNetwork.h"

#include "esp_log.h"
#include "mqtt_client.h"


static const char *TAG = __FILE_NAME__;

esp_mqtt_client_handle_t g_mqtt_client;

/* 订阅的主题 */
char g_mqtt_subject_subscribe_iot[80];
/* 发布的主题 */
char g_mqtt_subject_publish_app[80];
char g_mqtt_subject_publish_server[80];

static void log_error_if_nonzero(const char *message, int error_code)
{
    if (error_code != 0) {
        ESP_LOGE(TAG, "Last error %s: 0x%x", message, error_code);
    }
}

/*
 * @brief Event handler registered to receive MQTT events
 *
 *  This function is called by the MQTT client event loop.
 *
 * @param handler_args user data registered to the event.
 * @param base Event base for the handler(always MQTT Base in this example).
 * @param event_id The id for the received event.
 * @param event_data The data for the event, esp_mqtt_event_handle_t.
 */
static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data)
{
    ParametersType *ptypeParameters = ptypeParametersInfoGet();
    esp_mqtt_event_handle_t event = event_data;
    esp_mqtt_client_handle_t client = event->client;
    int msg_id;

    ESP_LOGD(TAG, "Event dispatched from event loop base=%s, event_id=%" PRIi32 "", base, event_id);

    switch ((esp_mqtt_event_id_t)event_id)
    {
        case MQTT_EVENT_ERROR:
            ESP_LOGI(TAG, "MQTT_EVENT_ERROR");
            if (event->error_handle->error_type == MQTT_ERROR_TYPE_TCP_TRANSPORT)
            {
                log_error_if_nonzero("reported from esp-tls", event->error_handle->esp_tls_last_esp_err);
                log_error_if_nonzero("reported from tls stack", event->error_handle->esp_tls_stack_err);
                log_error_if_nonzero("captured as transport's socket errno",  event->error_handle->esp_transport_sock_errno);
                ESP_LOGI(TAG, "Last errno string (%s)", strerror(event->error_handle->esp_transport_sock_errno));
            }
            break;

        case MQTT_EVENT_CONNECTED:
            ESP_LOGI(TAG, "MQTT_EVENT_CONNECTED");
            ptypeParameters->networkState |= BIT2;

            msg_id = esp_mqtt_client_subscribe(client, g_mqtt_subject_subscribe_iot, 0);
            ESP_LOGI(TAG, "sent subscribe: %s successful, msg_id=%d", g_mqtt_subject_subscribe_iot, msg_id);

            msg_id = esp_mqtt_client_publish(client, g_mqtt_subject_subscribe_iot, g_mqtt_subject_subscribe_iot, 0, 0, 0);
            ESP_LOGI(TAG, "sent publish: %s successful, msg_id=%d", g_mqtt_subject_subscribe_iot, msg_id);

            msg_id = esp_mqtt_client_publish(client, g_mqtt_subject_publish_server, g_mqtt_subject_publish_server, 0, 0, 0);
            ESP_LOGI(TAG, "sent publish: %s successful, msg_id=%d", g_mqtt_subject_publish_server, msg_id);

            msg_id = esp_mqtt_client_publish(client, g_mqtt_subject_publish_app, g_mqtt_subject_publish_app, 0, 0, 0);
            ESP_LOGI(TAG, "sent publish: %s successful, msg_id=%d", g_mqtt_subject_publish_app, msg_id);
            break;

        case MQTT_EVENT_DISCONNECTED:
            ESP_LOGI(TAG, "MQTT_EVENT_DISCONNECTED");
            ptypeParameters->networkState &= ~BIT2;
            break;

        case MQTT_EVENT_SUBSCRIBED:
            ESP_LOGI(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
            printf("TOPIC=%.*s\r\n", event->topic_len, event->topic);
            printf("DATA=%.*s\r\n", event->data_len, event->data);
            break;

        case MQTT_EVENT_UNSUBSCRIBED:
            ESP_LOGI(TAG, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event->msg_id);
            break;

        case MQTT_EVENT_PUBLISHED:
            ESP_LOGI(TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id);
            break;

        case MQTT_EVENT_DATA:
            ESP_LOGI(TAG, "MQTT_EVENT_DATA, msg_id: %d, topic: %.*s", event->msg_id, event->topic_len + event->data_len, event->topic);
            if(enumQueuePushDatas(&g_TypeQueueMqttRead, event->data, strlen(event->data) > event->data_len ? event->data_len : strlen(event->data)) != queueNormal)
                enumQueueClear(&g_TypeQueueMqttRead);
            vTaskNotifyGiveFromISR(g_TaskNetworkHand, NULL);
            break;

        case MQTT_EVENT_BEFORE_CONNECT:
            ESP_LOGI(TAG, "MQTT_EVENT_BEFORE_CONNECT, msg_id=%d", event->msg_id);
            break;

        default:
            ESP_LOGI(TAG, "Other event id:%d", event->event_id);
            break;
    }
}

int8_t mqtt_subject_init(void)
{
    ParametersType *ptypeParameters = ptypeParametersInfoGet();
    char *name;

    /* 发布的主题 - APP */
    memset(g_mqtt_subject_publish_app, 0, sizeof(g_mqtt_subject_publish_app));
    name = g_mqtt_subject_publish_app;
    sprintf(name, "/DBS/%s/app/qos0", ptypeParameters->UID);

    /* 发布的主题 - 服务器 */
    memset(g_mqtt_subject_publish_server, 0, sizeof(g_mqtt_subject_publish_server));
    name = g_mqtt_subject_publish_server;
    sprintf(name, "/DBS/%s/server/qos0", ptypeParameters->UID);

    /* 订阅的主题 - IOT */
    memset(g_mqtt_subject_subscribe_iot, 0, sizeof(g_mqtt_subject_subscribe_iot));
    name = g_mqtt_subject_subscribe_iot;
    sprintf(name, "/DBS/%s/iot/qos0", ptypeParameters->UID);

    return 0;
}

static void mqtt_tcp_app_start(void)
{
    ParametersType *ptypeParameters = ptypeParametersInfoGet();

    esp_mqtt_client_config_t mqtt_cfg = {
        .broker.address.uri = "mqtts://iotserver.dabbsson.cn",
        .credentials.username = "user",
        .credentials.authentication.password = "123456",
        // .broker.address.uri = "mqtt://honrun.top",
        // .credentials.username = "mqtt_tcp",
        // .credentials.authentication.password = "mqtt_tcp",
        .credentials.client_id = ptypeParameters->UID,
    };

    g_mqtt_client = esp_mqtt_client_init(&mqtt_cfg);

    /* The last argument may be used to pass data to the event handler, in this example mqtt_event_handler */
    esp_mqtt_client_register_event(g_mqtt_client, ESP_EVENT_ANY_ID, mqtt_event_handler, NULL);
    esp_mqtt_client_start(g_mqtt_client);
}

static void mqtt_ssl_app_start(void)
{
    extern const uint8_t mqtt_server_pem[] asm("_binary_mqtt_server_pem_start");
    ParametersType *ptypeParameters = ptypeParametersInfoGet();

    esp_mqtt_client_config_t mqtt_cfg = {
        .broker.verification.certificate = (const char *)mqtt_server_pem,
        .broker.address.uri = "mqtts://iotserver.dabbsson.cn:8883",
        .credentials.username = "user",
        .credentials.authentication.password = "123456",
        .credentials.client_id = ptypeParameters->UID,
    };

    g_mqtt_client = esp_mqtt_client_init(&mqtt_cfg);

    /* The last argument may be used to pass data to the event handler, in this example mqtt_event_handler */
    esp_mqtt_client_register_event(g_mqtt_client, ESP_EVENT_ANY_ID, mqtt_event_handler, NULL);
    esp_mqtt_client_start(g_mqtt_client);
}

void mqtt_init(void)
{
    mqtt_subject_init();

    mqtt_ssl_app_start();
}

int8_t mqtt_reconnect(void)
{
    mqtt_subject_init();

    return esp_mqtt_client_start(g_mqtt_client);
}

int8_t mqtt_disconnect(void)
{
    esp_mqtt_client_disconnect(g_mqtt_client);

    return esp_mqtt_client_stop(g_mqtt_client);
}

int8_t mqtt_datas_send_app(void *pvDatas, int32_t iLength)
{
    return esp_mqtt_client_publish(g_mqtt_client, g_mqtt_subject_publish_app, pvDatas, iLength, 0, 0);
}

int8_t mqtt_datas_send_server(void *pvDatas, int32_t iLength)
{
    return esp_mqtt_client_publish(g_mqtt_client, g_mqtt_subject_publish_server, pvDatas, iLength, 0, 0);
}
